<template>
    <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
        <span style="line-height:60px;font-size:20px;">新增围栏</span>
        <el-button type="primary" style="float:right;margin-top:13px;" @click="router.push('/geofence')">返回</el-button>

    </div>
<!--    第六步：创建地图容器元素-->
    <div style="width: 100%;height: 82vh;" id="mapContainer"></div>
<!--        新增电子围栏的弹窗-->
        <el-dialog v-model="dialogVisible" title="围栏信息" :before-close="closeDialog">
            <el-form label-width="80px">
                <el-form-item label="围栏名称">
                    <el-input v-model="geofence.name" placeholder="请输入围栏名称"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="saveGeofence">确定</el-button>
            </template>
        </el-dialog>

</template>

<script setup>
import router from "@/router";
import {nextTick, onMounted, ref} from "vue";
import { DrawScene, DrawControl ,OperateEventType } from 'bmap-draw';
import {ElMessage} from "element-plus";
import axios from "axios";
import qs from "qs";

var map;
onMounted(()=>{
    //表示在DOM更新之后执行，确保地图能在div容器之后渲染
nextTick(()=>{
    //第七步：创建地图实例，放入之前准备好的容器中
    map= new BMapGL.Map("mapContainer");
    //第八步：设置地图中心点
    let point =new BMapGL.Point(116.4047, 39.9042);
    //第九步：初始化地图，设置中心点坐标和地图缩放级别
    map.centerAndZoom(point, 15);
    // 添加鼠标绘制控件
    const scene = new DrawScene(map);
    const drawContrl = new DrawControl(scene, {
        enableTips: false,
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        drawingItems: [
            'circle',
            'rectangle'
        ]
    });
    //围栏绘制结束要添加监听事件，返回当前的电子围栏元素
    scene.addEventListener(OperateEventType.COMPLETE,(event)=>{
        //绘制完成，点击“V”,显示新增围栏弹窗
        dialogVisible.value=true;
        console.log(event.target);
        let overlay=event.target.overlay;
        if (overlay instanceof  BMapGL.Circle){
         geofence.value.position.type='circle';
         geofence.value.position.longitude=overlay.getCenter().lng;
         geofence.value.position.latitude=overlay.getCenter().lat;
         geofence.value.position.radious=overlay.getRadius();
         console.log(geofence.value.position);
        }else {
            //定义数组用来保存矩形的四个顶点坐标
            let recPoints = [];
            //依次获取矩形的四个顶点坐标并保存到数组中
            for(let i = 0; i < 4; i++){
                //overlay.points[i] 5个点 0,1,2,3循环四次,也就是依次获取四个顶点的经纬度值，存入recPoints数组中
                recPoints.push(overlay.points[i].latLng.lng+'-'+overlay.points[i].latLng.lat);
            }
            console.log(recPoints);
            //将数组中的元素用逗号分隔并保存到data对象中
            console.log(recPoints.join(','));
            //设置围栏类型为矩形
            geofence.value.position.type='rectangle';
            //将顶点坐标数组中的元素用逗号分隔并保存到position属性里
            geofence.value.position.recPoints = recPoints.join(',');
            console.log(geofence.value.position);//{type:'rectangle',recPoints:'116.38124134354936-39.91878313185032,116.38734982101722-39.91878313185032,116.38734982101722-39.91324913449542,116.38124134354936-39.91324913449542'}
        }
    })

    map.addControl(drawContrl);
})
})
const geofence=ref({
    name:'',
    position:{}
});

const dialogVisible=ref(false);


const saveGeofence=()=>{
    if (!geofence.value.name||geofence.value.name.trim().length==0){
        ElMessage.error('围栏名称不能为空');
        return;
    }
    let data=qs.stringify(geofence.value);
    axios.post(BASE_URL+'/v1/geofence/save',data)
        .then((response)=>{
            if (response.data.code==2000){
                ElMessage.success('保存成功');
                dialogVisible.value=false;
                router.push('/geofence');
            }else {
                ElMessage.error(response.data.msg);
            }
        })
}
const closeDialog=()=>{
    if (confirm('确定取消吗?')){
        dialogVisible.value=false;
        map.clearOverlays();
    }
}
</script>

<style scoped>

</style>